<?php
declare(strict_types=1);

/**
 * 阿里云经纬度归属地查询服务中心
 */
namespace Service\VendorClient\Aliyun;
use Service\BaseService;
use Service\Code\Normal;
use Service\ExtraService\IdService;
use App\Service\TaskServer\TaskWorker;
class AliyunLatlngtoAddressQueryClient extends BaseService
{
    protected $config;
    public function __construct(array $apiBody = [])
    {
        $this->config = $apiBody;
    }

    /**
     * 查询经纬度归属地址
     * @param string $lat
     * @param string $lng
     * @return int[]|string[]|array[]
     */
    public function queryAddressByLatLng(string $lat,string $lng)
    {
        if( empty($this->config['baseurl']) ) {
            return Normal::returnCode(Normal::FAIL,"当前阿里云查询经纬度归属地址baseurl未配置");
        }
        $url = $this->config['baseurl']."?lat={$lat}&lng={$lng}";
        $header = [
            "Authorization:APPCODE {$this->config['AppCode']}"
        ];        
        $parameter = [
            [
                'tag'       => 'aliyun_latlngto_query',
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => [],
                'method'    => 'GET',
                'format'    => 'x-www-form-urlencoded',
                'header'    => $header,
            ],
        ];
        $resTask    = TaskWorker::instance()->addTask($parameter);
        $resTask    = current($resTask);
        $res        = $resTask['response']['result'];
        $resHttp    = json_decode($res, true);
        $errorMsg   = $resHttp['resp']['RespMsg'] ?? '阿里云经纬度地址归属查询请求失败，请联系阿里云客服解决!';
        if (isset($resHttp['resp']['RespCode']) && $resHttp['resp']['RespCode'] == '0') {
            return Normal::returnCode(Normal::SUC, "操作成功",[
                'province'  => $resHttp['data']['province'],
                'city'      => $resHttp['data']['city'],
                'district'  => $resHttp['data']['district'] ??'',
                'lat'       => $lat,
                'lng'       => $lng
            ]);
        }
        return Normal::returnCode(Normal::FAIL, $errorMsg);
    }
}